﻿import com.dmotiko.general.*;
import mx.transitions.*;
import mx.transitions.easing.*;
/**
 * ...
 * @author sminutoli
 */
class com.dmotiko.meip.ProductoScroll extends BaseClip
{
	private var drag:MovieClip;
	private var bar:MovieClip;
	private var next:MovieClip;
	private var prev:MovieClip;
	private var nPos:Number;
	private var nFraction:Number;
	
	private function initClip():Void {
		drag._x = bar._x;
		nPos = 1;
		nFraction = bar._width / 7;
		
		var root:ProductoScroll = this;
		
		drag.onPress = function() {
			this.pressed = true;
			this.startDrag( false, root.bar._x, this._y, root.bar._x + root.bar._width - this._width, this._y );
			root.checkPos();
			
		}
		drag.onRelease = function() {
			this.pressed = false;
			this.stopDrag();
			root.checkPos(false);
		}
		drag.onReleaseOutside = drag.onRelease;
		
		next.onRelease = function() {
			var actualPos = (Math.round(root.drag._x / root.nFraction));
			var nX:Number;
			if (actualPos == 6 ) {
				nX = root.bar._x + root.bar._width - root.drag._width;
								
			} else if (actualPos < 6) {
				nX = root.nFraction * (actualPos + 1) - root.drag._width + 3;
				
			} else {
				return;
			}
			root.registerTween( "dragMove", new Tween( root.drag, "_x", Regular.easeInOut, root.drag._x, nX, 0.3, true), false, true );
			root.checkPos();
		}
		
		prev.onRelease = function() {
			var actualPos = (Math.round(root.drag._x / root.nFraction));
			var nX:Number;
			if (actualPos == 2 ) {
				nX = root.bar._x;
				
			} else if ( actualPos > 2 ) {
				nX = root.nFraction * (actualPos - 1) - root.drag._width + 3;
				
			} else {
				return;
			}
			root.registerTween( "dragMove", new Tween( root.drag, "_x", Regular.easeInOut, root.drag._x, nX, 0.3, true), false, true );
			root.checkPos();			
		}
	}
	
	private function tweenFinished(key:String, tween:Tween):Void {
		if( !drag.pressed ) checkPos(false);
	}
	
	public function setPos(newPos, moveDrag:Boolean):Void {
		nPos = newPos;
		if (moveDrag) {
			drag._x = nFraction * newPos - drag._width;
		}
		dispatchEvent( { type: BaseClipEvent.CHANGED, target: this, data: nPos } );
	}
	
	private function checkPos(check:Boolean):Void {
		if (check == false) {
			delete this.onEnterFrame;
			return;
		};
		this.onEnterFrame = function() {
			
			var newPos = (Math.round(drag._x / nFraction));
			if (newPos != nPos) {
				setPos( newPos );
			}
		}
	}
	
}